package com.my.study.globalfilter.normal;

import com.my.study.aop.annotation.FilterType;
import com.my.study.enums.ApiTypeEnum;
import com.my.study.util.HttpGlobalUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 访问域名校验
 */
@Component
public class RefererFilter implements GlobalFilter, Ordered {

    @Value("${referer.enable:false}")
    private boolean enable;
    @Value("${referer.whiteList}")
    private String whiteList;


    @FilterType(type = ApiTypeEnum.NORMAL_API)
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> list =Arrays.asList(whiteList.split(","));
        ServerHttpRequest request = exchange.getRequest();
        String host = request.getHeaders().getFirst("host");
        // 校验是否开启
        if(enable){
            // 白名单校验
            if(isWhiteList(list,host)){
                return chain.filter(exchange);
            }else {
                return HttpGlobalUtil.fail(exchange.getResponse());
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -2;
    }

    /**
     * 检查是否配置白名单
     *
     * @param list
     * @param url
     * @return
     */
    private boolean isWhiteList(List<String> list,String url){
        for(String str:list){
            if(url.contains(str)){
                return true;
            }
        }
        return false;
    }
}
